import axios from 'axios'
import type { User } from '@/types'

const api = axios.create({
  baseURL: 'http://localhost:5000/api',
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 响应拦截器
api.interceptors.response.use(
  response => response.data,
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
    }
    return Promise.reject(error.response?.data || error)
  }
)

interface LoginResponse {
  token: string
  user: User
}

interface LoginCredentials {
  username: string
  password: string
  userType: string
}

interface RegisterData {
  username: string
  password: string
  email: string
}

export const login = (credentials: LoginCredentials): Promise<LoginResponse> => {
  return api.post('/auth/login', credentials)
}

export const register = (userData: RegisterData): Promise<LoginResponse> => {
  return api.post('/auth/register', userData)
}

export const getCurrentUser = (): Promise<User> => {
  return api.get('/auth/me')
}

export default api 